package study2018.com.xtianzhuang.www.luncene;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.log4j.Logger;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

public class LunceneWriter {
	private static Logger logger = Logger.getLogger(LunceneWriter.class);
	private static final String INDEX_PATH = "D:\\study\\luncene\\index";
	private static final String RESOURCE_PATH = "D:\\study\\luncene\\source";

	public static void main(String[] args) throws IOException {
		Directory directory = FSDirectory.open(new File(INDEX_PATH));
		IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LUCENE_36, new StandardAnalyzer(Version.LUCENE_36));
		indexWriterConfig.setOpenMode(OpenMode.CREATE);
		IndexWriter indexWriter = new IndexWriter(directory, indexWriterConfig);

		File[] files = new File(RESOURCE_PATH).listFiles();
		for (File f : files) {
			logger.debug("File " + f.getCanonicalPath() + "正在被索引");
			String context = FileReaderAll(f.getCanonicalPath(), "GBK");
			logger.info("File context{} " + context);
			Document document = new Document();
			Field field = new Field("context", context, Field.Store.YES, Field.Index.ANALYZED);
			document.add(field);
			indexWriter.addDocument(document);
		}
		indexWriter.close();
	}

	public static String FileReaderAll(String FileName, String charset) throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(FileName), charset));
		String line = new String();
		String temp = new String();

		while ((line = reader.readLine()) != null) {
			temp += line;
		}
		reader.close();
		return temp;
	}
}
